import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/404',
    name: 'Notfound',
    component: () => import('../views/Notfound.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 重置路由方法
export const resetRouter = () => {
  router.matcher = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  })
}

export const setRoutes = () => {
  const storeMenus = localStorage.getItem("menus");
  // 拼装动态路由
  if (storeMenus) {
    const currentRouteNames = router.getRoutes().map(v => v.name)
    if (!currentRouteNames.includes('Manage')) {
      const manageRoute = { path: '/', name: 'Manage', component: () => import('../views/Manage.vue'), redirect: "/home", children: [
        { path: 'person', name: 'Person', component: () => import('../views/Person.vue')},
        { path: 'password', name: 'Password', component: () => import('../views/Password.vue')},
      ] }
      const menus = JSON.parse(storeMenus)
      menus.forEach(item => {
        if (item.path) {
          let itemMenu = { path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue') }
          manageRoute.children.push(itemMenu)
        } else if(item.children.length) {
          item.children.forEach(item => {
            if (item.path) {
              let itemMenu = { path: item.path.replace("/", ""), name: item.name, component: () => import('../views/' + item.pagePath + '.vue') }
              manageRoute.children.push(itemMenu)
            }
          })
        }
      });
      // 动态添加到现在的路由对象中去
    router.addRoute(manageRoute)
    }
  }
}

setRoutes()

router.beforeEach((to, from, next) => { 
  if (!to.matched.length) {
    const storeManus = localStorage.getItem("menus")
    if (storeManus) {
      next("/404")
    } else {
      next("/login")
    }
  }
  next()
})

export default router
